package com.yy.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;

import com.yy.config.AlipayConfig;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述
 * 作者 yy
 */
@RestController
public class CallBackController {
    @RequestMapping("callback")
    public void callback(HttpServletRequest request){
        Map<String, String> parameterMap = getParameterMap(request);
        try {
            //判断是否为支付宝调用
            boolean singVerified = AlipaySignature.rsaCheckV1(parameterMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            System.out.println(singVerified);//只有支付宝调用我们系统的接口才能去更新系统订单状态
            System.out.println("验证签名结果:"+singVerified);
            if(singVerified){
                String tradeStatus = parameterMap.get("trade_status");
                if(tradeStatus.equals("TRADE_SUCCESS")){
                    System.out.println("交易成功");
                    String outTradeNo = parameterMap.get("out_trade_no");//自己系统里面的单号
                    String tradeNo = parameterMap.get("trade_no");//支付宝那边的订单ID
                    String refundFee = parameterMap.get("refund_fee");//退款金额
                    System.out.println(outTradeNo);
                    System.out.println(tradeNo);
                    System.out.println(refundFee);
                    if (StringUtils.hasText(refundFee)) {
                        //退款成功
                        System.out.println("退款成功");
                    }else{
                        //支付成功
                        System.out.println("支付成功");
                    }

                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            System.out.println("验证签名出现异常");
        }
        System.out.println("结束");
    }
    /**
     * 获取request中的参数集合转Map
     * Map<String,String> parameterMap = RequestUtil.getParameterMap(request)
     * @param request
     * @return
     */
    public Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
}
